# -*- coding: utf-8 -*-

from odoo import models, fields, api
import os
import sys
import requests
from requests.auth import HTTPBasicAuth
import json

import logging

_logger = logging.getLogger(__name__)

cert = ("/odoo/apps/myaddons/watermeter/static/src/cert/client.crt",
        "/odoo/apps/myaddons/watermeter/static/src/cert/client.key")

class waterMeter(models.Model):
    _name = 'watermeters.watermeter'
    _rec_name = 'device_id'

    table_no = fields.Integer(string=u'表号', readonly=True)
    balance = fields.Float(string=u'剩余金额', digits=(16, 3), readonly=True)
    sum_of_amount = fields.Float(string=u'累充金额', digits=(16, 2), readonly=True)
    sum_of_flow = fields.Float(string=u'累计流量', digits=(16, 1), readonly=True)
    table_state = fields.Char(string=u'表状态', readonly=True)
    device_id = fields.Char(string=u'设备号', readonly=True)
    upload_time = fields.Char(string=u'上报时间', readonly=True)
    test_ids = fields.One2many('watermeters.test', 'watermeter_id', string=u'历史数据')
    IMEI = fields.Char(string=u'设备唯一标识', required=True)
    model = fields.Selection([
        ('Z500LD', u'Z500LD'),
        ('0103C', u'0103C')
    ], string=u'设备型号', required=True, default='0103C')
    manufacturerName = fields.Selection([
        ('BCMETERC', u'BCMETERC'),
        ('FeiAo', u'FeiAo')
    ], string=u'厂商名称', readonly=True, compute='_set_model', store=True)
    device_type = fields.Selection([
        ('WaterMeter', u'WaterMeter'),
        ('NBIoT', u'NBIoT')
    ], string=u'设备类型', readonly=True, compute='_set_model', store=True)

    @api.depends('model')
    def _set_model(self):
        for rec in self:
            if rec.model == 'Z500LD':
                rec.manufacturerName = 'FeiAo'
                rec.device_type = 'NBIoT'
            elif rec.model == '0103C':
                rec.manufacturerName = 'BCMETERC'
                rec.device_type = 'WaterMeter'

    @api.multi
    def check_history(self):
        for rec in self:
            tests = rec.env['watermeters.test'].search([
                ('table_no', '=', rec.table_no),
                # ('device_id', '=', rec.device_id)
            ])
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'watermeters.test',
                'view_mode': 'tree',
                'view_type': 'tree',
                'domain': [('id', 'in', tests.ids)],
                # 'res_id': tests,
                'context': {
                    'device_id': rec.device_id,
                },
            }

    @api.multi
    def btn_auth(self):
        app_id = self.env['ir.config_parameter'].get_param('app_id')
        secret = self.env['ir.config_parameter'].get_param('secret')
        params = {
            'appId': app_id,
            'secret': secret
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        response = requests.post(url="https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login", data=params, cert=cert,
                                 verify=False, headers=headers)
        response = json.loads(response.text)
        access_token = response.get('accessToken')
        return access_token

    @api.multi
    def btn_regist(self):
        app_id = self.env['ir.config_parameter'].get_param('app_id')
        access_token = self.btn_auth()
        url = "https://180.101.147.89:8743/iocm/app/reg/v1.1.0/devices"
        params = {
            'verifyCode': self.IMEI,
            'nodeId': self.IMEI,
            # 'verifyCode': '863703030620921',
            # 'nodeId': '863703030620921',
            'timeout': 0
        }

        headers = {
            'app_key': app_id,
            'Authorization': 'Bearer %s' % access_token,
            'Content-Type': 'application/json'
        }
        response = requests.post(url=url, data=json.dumps(params), cert=cert,
                                 verify=False, headers=headers)
        response = json.loads(response.text)
        self.device_id = response.get('deviceId')
        _logger.info(response)

    @api.multi
    def btn_bind(self):
        app_id = self.env['ir.config_parameter'].get_param('app_id')
        access_token = self.btn_auth()
        url = "https://180.101.147.89:8743/iocm/app/dm/v1.1.0/devices/%s" % self.device_id
        params = {
            'name': self.table_no,
            'model': self.model,
            'manufacturerId': self.manufacturerName,
            'manufacturerName': self.manufacturerName,
            'deviceType': self.device_type,
            'protocolType': 'CoAP',
            'location': 'CN'
        }
        headers = {
            'app_key': app_id,
            'Authorization': 'Bearer %s' % access_token,
            'Content-Type': 'application/json'
        }
        response = requests.put(url=url, data=json.dumps(params), cert=cert, verify=False, headers=headers)
        _logger.info(response)
